
import { useState } from "react";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { Calendar } from "@/components/ui/calendar";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { CalendarIcon, Plus, Target, X } from "lucide-react";
import { format } from "date-fns";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Progress } from "@/components/ui/progress";
import { Badge } from "@/components/ui/badge";

interface Goal {
  id: string;
  title: string;
  description: string;
  type: 'Knowledge' | 'Skill' | 'Habit';
  term: 'Short-term' | 'Long-term';
  deadline: Date | undefined;
  progress: number;
  completed: boolean;
}

interface GoalSettingModalProps {
  onClose: () => void;
}

export function GoalSettingModal({ onClose }: GoalSettingModalProps) {
  const [isOpen, setIsOpen] = useState(true);
  const [goals, setGoals] = useState<Goal[]>([]);
  const [showAddForm, setShowAddForm] = useState(false);
  const [newGoal, setNewGoal] = useState({
    title: '',
    description: '',
    type: '' as Goal['type'] | '',
    term: '' as Goal['term'] | '',
    deadline: undefined as Date | undefined
  });

  const handleClose = () => {
    setIsOpen(false);
    onClose();
  };

  const handleAddGoal = () => {
    if (!newGoal.title || !newGoal.type || !newGoal.term) return;

    const goal: Goal = {
      id: Date.now().toString(),
      title: newGoal.title,
      description: newGoal.description,
      type: newGoal.type,
      term: newGoal.term,
      deadline: newGoal.deadline,
      progress: 0,
      completed: false
    };

    setGoals([...goals, goal]);
    setNewGoal({
      title: '',
      description: '',
      type: '',
      term: '',
      deadline: undefined
    });
    setShowAddForm(false);
  };

  const updateGoalProgress = (goalId: string, progress: number) => {
    setGoals(goals.map(goal => 
      goal.id === goalId 
        ? { ...goal, progress, completed: progress >= 100 }
        : goal
    ));
  };

  const deleteGoal = (goalId: string) => {
    setGoals(goals.filter(goal => goal.id !== goalId));
  };

  return (
    <Dialog open={isOpen} onOpenChange={handleClose}>
      <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Target className="w-5 h-5 text-blue-600" />
            Set Learning Goals
          </DialogTitle>
        </DialogHeader>

        <div className="space-y-6">
          {/* Add New Goal Form */}
          {showAddForm ? (
            <Card>
              <CardHeader>
                <CardTitle className="text-lg">Add New Goal</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <Label htmlFor="title">Goal Title *</Label>
                    <Input
                      id="title"
                      value={newGoal.title}
                      onChange={(e) => setNewGoal({...newGoal, title: e.target.value})}
                      placeholder="e.g., Finish 3 chapters this week"
                    />
                  </div>
                  
                  <div>
                    <Label>Goal Type *</Label>
                    <Select value={newGoal.type} onValueChange={(value: Goal['type']) => setNewGoal({...newGoal, type: value})}>
                      <SelectTrigger>
                        <SelectValue placeholder="Select type" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="Knowledge">Knowledge</SelectItem>
                        <SelectItem value="Skill">Skill</SelectItem>
                        <SelectItem value="Habit">Habit</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <Label>Time Frame *</Label>
                    <Select value={newGoal.term} onValueChange={(value: Goal['term']) => setNewGoal({...newGoal, term: value})}>
                      <SelectTrigger>
                        <SelectValue placeholder="Select time frame" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="Short-term">Short-term (days to weeks)</SelectItem>
                        <SelectItem value="Long-term">Long-term (months to years)</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>

                  <div>
                    <Label>Deadline</Label>
                    <Popover>
                      <PopoverTrigger asChild>
                        <Button variant="outline" className="w-full justify-start text-left font-normal">
                          <CalendarIcon className="mr-2 h-4 w-4" />
                          {newGoal.deadline ? format(newGoal.deadline, "PPP") : "Pick a date"}
                        </Button>
                      </PopoverTrigger>
                      <PopoverContent className="w-auto p-0">
                        <Calendar
                          mode="single"
                          selected={newGoal.deadline}
                          onSelect={(date) => setNewGoal({...newGoal, deadline: date})}
                          initialFocus
                        />
                      </PopoverContent>
                    </Popover>
                  </div>
                </div>

                <div>
                  <Label htmlFor="description">Description</Label>
                  <Textarea
                    id="description"
                    value={newGoal.description}
                    onChange={(e) => setNewGoal({...newGoal, description: e.target.value})}
                    placeholder="Describe your goal in more detail..."
                    rows={3}
                  />
                </div>

                <div className="flex gap-2">
                  <Button onClick={handleAddGoal}>Add Goal</Button>
                  <Button variant="outline" onClick={() => setShowAddForm(false)}>Cancel</Button>
                </div>
              </CardContent>
            </Card>
          ) : (
            <Button onClick={() => setShowAddForm(true)} className="w-full">
              <Plus className="w-4 h-4 mr-2" />
              Add New Goal
            </Button>
          )}

          {/* Goals List */}
          <div className="space-y-4">
            <h3 className="text-lg font-semibold">Your Goals ({goals.length})</h3>
            
            {goals.length === 0 ? (
              <Card>
                <CardContent className="text-center py-8">
                  <Target className="w-12 h-12 text-gray-400 mx-auto mb-4" />
                  <p className="text-gray-600">No goals set yet. Add your first goal to get started!</p>
                </CardContent>
              </Card>
            ) : (
              <div className="grid gap-4">
                {goals.map((goal) => (
                  <Card key={goal.id}>
                    <CardContent className="p-4">
                      <div className="flex items-start justify-between mb-3">
                        <div>
                          <h4 className="font-semibold">{goal.title}</h4>
                          {goal.description && (
                            <p className="text-sm text-gray-600 mt-1">{goal.description}</p>
                          )}
                        </div>
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => deleteGoal(goal.id)}
                        >
                          <X className="w-4 h-4" />
                        </Button>
                      </div>
                      
                      <div className="flex items-center gap-2 mb-3">
                        <Badge variant={goal.type === 'Knowledge' ? 'default' : goal.type === 'Skill' ? 'secondary' : 'outline'}>
                          {goal.type}
                        </Badge>
                        <Badge variant="outline">{goal.term}</Badge>
                        {goal.deadline && (
                          <Badge variant="outline">
                            Due: {format(goal.deadline, "MMM dd")}
                          </Badge>
                        )}
                      </div>

                      <div className="space-y-2">
                        <div className="flex items-center justify-between text-sm">
                          <span>Progress</span>
                          <span>{goal.progress}%</span>
                        </div>
                        <Progress value={goal.progress} className="h-2" />
                        <div className="flex gap-2">
                          <Button
                            size="sm"
                            variant="outline"
                            onClick={() => updateGoalProgress(goal.id, Math.min(100, goal.progress + 25))}
                          >
                            +25%
                          </Button>
                          <Button
                            size="sm"
                            variant="outline"
                            onClick={() => updateGoalProgress(goal.id, 100)}
                          >
                            Complete
                          </Button>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                ))}
              </div>
            )}
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}
